﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace RWProxyDemo.Utils
{
    /// <summary>
    /// HttpClient
    /// </summary>
    public static class HttpClientHelper
    {
        /// <summary>
        /// 请求
        /// </summary>
        /// <typeparam name="T">参数T</typeparam>
        /// <param name="url">服务地址</param>
        /// <param name="route">路由地址</param>
        /// <param name="t">请求参数</param>
        /// <param name="headers">请求头</param>
        /// <param name="requestType">求情类型</param>
        /// <returns></returns>
        public static string Request<T>(string url, string route, T t, Dictionary<string, string> headers = null, RequestType requestType = RequestType.Post)
        {
            string result = "";
            using (HttpClient httpClient = new HttpClient())
            {
                if (headers != null)
                    foreach (KeyValuePair<string, string> keyValue in headers)
                        httpClient.DefaultRequestHeaders.Add(keyValue.Key, keyValue.Value);

                var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(t), Encoding.UTF8, "application/json");
                HttpResponseMessage response = requestType == RequestType.Post ? httpClient.PostAsync(url + route, content).Result : httpClient.GetAsync(url + route).Result;
                //确保Http响应成功
                if (response.IsSuccessStatusCode)
                    result = response.Content.ReadAsStringAsync().Result;
            }
            return result;
        }

        /// <summary>
        /// 调用的事例代码
        /// </summary>
        /// <returns></returns>
        private static string Test()
        {
            object o = new object();
            string url = ConsulHelper.GetServiceUrl("ZH.RetailContainer.OrderService");
            string method = "V1/Order/UpdateOrderStatus";
            string resultStr = HttpClientHelper.Request<object>(url, method, o);
            return resultStr;
        }
    }


    /// <summary>
    /// HttpClientHelper的请求方式
    /// </summary>
    public enum RequestType
    {
        /// <summary>
        /// Post请求
        /// </summary>
        Post = 0,
        /// <summary>
        /// Get请求
        /// </summary>
        Get = 1
    }
}
